<template>
  <div class="user-wrapper">
    <Form :model="formRight" label-position="right" :label-width="80">
      <Row :gutter="10">
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="用户名：">
            <Input v-model="formRight.username" placeholder="请输入用户名"></Input>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="手机号：">
            <Input v-model="formRight.phone" placeholder="请输入手机号"></Input>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="邮箱：">
            <Input v-model="formRight.email" placeholder="请输入邮箱"></Input>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem>
            <Button type="primary" @click="queryUser" shape="circle" icon="ios-search">查询</Button>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div class="tool-box">
      <Button type="primary" icon="md-add" ghost @click="addUserModel = true">添加用户</Button>
      <Button type="error" icon="md-trash" ghost style="margin-left:10px;">批量删除</Button>
    </div>
    <Table :loading="loading" border ref="selection" :columns="columns" :data="tableData"></Table>
    <div class="page-wrapper">
      <Page :total="total" @on-change="handlePage" show-elevator show-total/>
    </div>

    <div class="add-user">
      <Drawer title="添加用户" :mask-closable="false" v-model="addUserModel" :styles="styles" width="30">
        <Form ref="formInline" :model="formData" :rules="ruleInline">
          <Row :gutter="10">
            <Col span="24">
              <FormItem label="账号" prop="account" label-position="top">
                  <Input v-model="formData.account" placeholder="请输入账号，必填" />
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="密码" prop="password" label-position="top">
                  <Input v-model="formData.password" placeholder="请输入密码，必填" />
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="用户名" label-position="top">
                <Input v-model="formData.username" placeholder="请输入用户名"/>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="手机号" prop="phone" label-position="top">
                <Input v-model="formData.phone" placeholder="请输入手机号"/>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="邮箱" prop="email" label-position="top">
                <Input v-model="formData.email" placeholder="请输入邮箱"/>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="备注" label-position="top">
                <Input v-model="formData.note" placeholder="用户信息备注"/>
              </FormItem>
            </Col>
            <Col span="24">
              <Col :span="12" style="padding-right: 10px;">
                <FormItem label="用户状态">
                  <Select v-model="formData.state" placeholder="请选择用户状态">
                    <Option value="S">启用</Option>
                    <Option value="F">停用</Option>
                    <Option value="L">锁定</Option>
                    <Option value="A">弃用</Option>
                    <Option value="V">审核中</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col :span="12">
                <FormItem label="分配角色">
                  <Select v-model="formData.roleId" placeholder="请选择角色">
                    <Option v-for="item in roleList" :value="item.id" :key="item.id">{{item.roleName}}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Col>
          </Row>
        </Form>
        <div class="demo-drawer-footer">
          <Button style="margin-right: 8px" @click="addUserModel = false">关闭</Button>
          <Button type="primary" @click="handleAddUser" :loading="loadingAdd">
            <span v-if="!loadingAdd">提交</span>
            <span v-else>正在提交</span>
          </Button>
        </div>
      </Drawer>
    </div>

    <div class="edit-user">
      <Drawer title="修改用户信息" :mask-closable="false" v-model="editUserModel" :styles="styles" width="30">
        <Form ref="editFormInline" :model="editFormData" :rules="ruleInlineEdit">
          <Row :gutter="10">
            <Col span="24">
              <FormItem label="用户名" label-position="top">
                <Input v-model="editFormData.username" placeholder="请输入用户名"/>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="手机号" prop="phone" label-position="top">
                <Input v-model="editFormData.phone" placeholder="请输入手机号"/>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="邮箱" prop="email" label-position="top">
                <Input v-model="editFormData.email" placeholder="请输入邮箱"/>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="备注" label-position="top">
                <Input v-model="editFormData.note" placeholder="用户信息备注"/>
              </FormItem>
            </Col>
            <Col span="24">
              <Col :span="12" style="padding-right: 10px;">
                <FormItem label="用户状态">
                  <Select v-model="editFormData.state" placeholder="请选择用户状态">
                    <Option value="S">启用</Option>
                    <Option value="F">停用</Option>
                    <Option value="L">锁定</Option>
                    <Option value="A">弃用</Option>
                    <Option value="V">审核中</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col :span="12">
                <FormItem label="分配角色">
                  <Select v-model="editFormData.roleId" placeholder="请选择角色">
                    <Option v-for="item in roleList" :value="item.id" :key="item.id">{{item.roleName}}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Col>
          </Row>
        </Form>
        <div class="demo-drawer-footer">
          <Button style="margin-right: 8px" @click="editUserModel = false">关闭</Button>
          <Button type="primary" @click="handleEditUser" :loading="loadingEdit">
            <span v-if="!loadingEdit">提交</span>
            <span v-else>正在提交</span>
          </Button>
        </div>
      </Drawer>
    </div>
  </div>
</template>

<script>
import {getUserList,checkAccount,checkPhone,checkEmail,addUser,getAllRole,editUser,deleteUser} from '@/api/user'

/**
 * 账号验证
 */
const validateAccount = (rule, value, callback) => {
  checkAccount(value).then(res => {
    if(res.data.status){
      callback()
    }else{
      callback(new Error(res.data.msg))
    }
  })
}

const validatePhone = (rule, value, callback) => {
  if(value !== '' && value != null && value != 'null'){
    let reg = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/
    if(reg.test(value)){
      checkPhone({'phone': value}).then(res => {
        if(res.data.status){
          callback()
        }else{
          callback(new Error(res.data.msg))
        }
      })
    }else{
      callback(new Error('手机号不正确'))
    }
  }else{
    callback()
  }
}

const validateEmail = (rule, value, callback) => {
  if(value !== '' && value != null && value != 'null'){
    let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if(reg.test(value)){
      checkEmail({'email': value}).then(res => {
        if(res.data.status){
          callback()
        }else{
          callback(new Error(res.data.msg))
        }
      })
    }else{
      callback(new Error('邮箱格式不正确'))
    }
  }else{
    callback()
  }
}

export default {
  name: 'Users',
  data(){
    const validateEditPhone = (rule, value, callback) => {
      if(value && value.trim() != ''){
        let reg = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/
        if(reg.test(value)){
          checkPhone({'phone': value, 'userId': this.editFormData.id}).then(res => {
            if(res.data.status){
              callback()
            }else{
              callback(new Error(res.data.msg))
            }
          })
        }else{
          callback(new Error('手机号不正确'))
        }
      }else{
        callback()
      }
    }

    const validateEditEmail = (rule, value, callback) => {
      if(value && value.trim() != ''){
        let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if(reg.test(value)){
          checkEmail({'email': value, 'userId': this.editFormData.id}).then(res => {
            if(res.data.status){
              callback()
            }else{
              callback(new Error(res.data.msg))
            }
          })
        }else{
          callback(new Error('邮箱格式不正确'))
        }
      }else{
        callback()
      }
    }

    return {
      formRight: {
        username: '',
        phone: '',
        email: ''
      },
      tableData: [],
      total:0,
      loading: true,
      columns: [
        {
          type: 'selection',
          align: 'center',
          width: 60,
          fixed: 'left'
        },
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '用户',
          key: 'username',
          minWidth: 150,
          render: (h, params) => {
            return h('div', [
              h('Avatar', {
                props: {
                  src: params.row.userImg
                },
                style: {
                  marginRight: '8px'
                }
              }),
              h('strong', params.row.username)
            ]);
          }
        },
        {
          title: '账号',
          key: 'account',
          minWidth: 150,
        },
        {
          title: '手机号',
          key: 'phone',
          minWidth: 150,
        },
        {
          title: '邮箱',
          key: 'email',
          minWidth: 150,
        },
        {
          title: '状态',
          key: 'state',
          minWidth: 100,
          render: (h, params) => {
            return this.getUserStateTag(h,params)
          }
        },
        {
          title: '角色',
          key: 'roleName',
          minWidth: 150,
        },
        {
          title: '备注',
          key: 'note',
          minWidth: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          minWidth: 170
        },
        {
          title: '更新时间',
          key: 'updateTime',
          minWidth: 170
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 130,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.editUserModel = true
                    this.editFormData = {...params.row}
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除用户',
                      content: '您确认要删除用户<strong>'+params.row.account+'</strong>?',
                      onOk: () => {
                        deleteUser(params.row.id).then(res =>{
                          if(res.data.status){
                            this.$Message.success('删除成功')
                            this.tableData.forEach((item,index, arr) => {
                              if(item.account === params.row.account){
                                arr.splice(index, 1)
                                this.total = this.total - 1
                              }
                            })
                          }
                        })
                      }
                    })
                  }
                }
              }, '删除')
            ]);
          }
        }
      ],
      addUserModel: false,
      styles: {
        background: '#fff',
        padding: '10px'
      },
      formData: {
        account: '',
        password: '',
        username: '',
        phone: '',
        email: '',
        note: '',
        state: 'S',
        roleId: ''
      },
      ruleInline: {
        account: [
          { required: true, message: '账号不能为空'},
          { validator: validateAccount, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空'}
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
      },
      ruleInlineEdit: {
        phone: [
          { validator: validateEditPhone, trigger: 'blur' }
        ],
        email: [
          { validator: validateEditEmail, trigger: 'blur' }
        ]
      },
      loadingAdd: false,
      roleList: [],
      editUserModel: false,
      editFormData: {
        account: '',
        username: '',
        phone: '',
        email: '',
        note: '',
        state: '',
        roleId: ''
      },
      loadingEdit: false,
    }
  },
  methods:{
    /**
     * 分页处理
     */
    handlePage(pageNum){
      this.loading = true
      getUserList({
        pageSize: 10,
        pageNum: pageNum,
        username: this.formRight.username,
        phone: this.formRight.phone,
        email: this.formRight.email
      }).then(res =>{
        this.loading = false
        this.tableData = res.data.data.list == null ? [] : res.data.data.list
        this.total = res.data.data.total
      })
    },
    /**
     * 查询用户
     */
    queryUser(){
      this.loading = true
      getUserList({
        pageSize: 10,
        pageNum: 1,
        username: this.formRight.username,
        phone: this.formRight.phone,
        email: this.formRight.email
      }).then(res =>{
        this.loading = false
        this.tableData = res.data.data.list == null ? [] : res.data.data.list
        this.total = res.data.data.total
      }).catch(()=>{
        this.loading = false
      })
    },
    /**
     * 获取用户状态标签
     */
    getUserStateTag(h, params){
      let color;
      let text;
      let state = params.row.state
      if(state === 'A'){
        color = 'default'
        text = '弃用'
      }else if(state === 'F'){
        color = 'error'
        text = '停用'
      }else if(state === 'S'){
        color = 'success'
        text = '启用'
      }else if(state === 'L'){
        color = 'warning'
        text = '锁定'
      }else if(state === 'V'){
        color = 'primary'
        text = '审核中'
      }else {
        color = 'blue'
        text = '未知'
      }
      return h('div', [
        h('Tag', {
          props: {
            color: color
          }
        }, text)
      ])
    },
    handleAddUser(){
      this.loadingAdd = true
      this.$refs['formInline'].validate((valid) => {
        if(valid){
          let data = {
            account: this.formData.account,
            password: this.formData.password,
            state: this.formData.state
          }
          if(this.formData.phone){
            data.phone = this.formData.phone
          }
          if(this.formData.email){
            data.email = this.formData.email
          }
          if(this.formData.note){
            data.note = this.formData.note
          }
          if(this.formData.username){
            data.username = this.formData.username
          }
          if(this.formData.roleId){
            data.roleId = this.formData.roleId
          }
          addUser(data).then(res => {
            this.loadingAdd = false
            if(res.data.status){
              this.$Message.success({
                content: '添加用户成功'
              })
              this.queryUser()
              this.addUserModel = false
            }
          }).catch(() => {
            this.loadingAdd = false
          })
        }else{
          this.loadingAdd = false
        }
      })
    },
    /**
     * 角色下拉列表数据获取
     */
    getRoles(){
      getAllRole().then(res => {
        if(res.data.status){
          this.roleList = res.data.data
        }
      })
    },
    /**
     * 处理修改用户信息
     */
    handleEditUser(){
      this.loadingEdit = true
      this.$refs['editFormInline'].validate((valid) => {
        if(valid){
          editUser(this.editFormData).then(res => {
            this.loadingEdit = false
            if(res.data.status){
              const result = res.data.data
              this.$Message.success({
                content: '修改用户信息成功'
              })
              let resultArr = []
              this.tableData.forEach((item,index,arr) => {
                if(item.id === result.id){
                  resultArr[index] = result
                }else{
                  resultArr[index] = item
                }
              })
              this.tableData = resultArr
              this.editUserModel = false
            }
          }).catch(() => {
            this.loadingEdit = false
          })
        }else{
          this.loadingEdit = false
        }
      })
    }
  },
  created(){
    //初始化表格数据
    this.queryUser()
    //初始化角色下拉列表数据
    this.getRoles()
  }
}
</script>

<style lang="less">
.user-wrapper{
  padding: 10px;
  .tool-box{
    padding: 10px;
    padding-left: 0;
  }
  .page-wrapper{
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .demo-drawer-footer{
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
}
</style>
